<template>
  <div class="wrapper">
    <div v-loading="loading" class="gathering">
      <canvas id="canvas" :width="`${width}px`" :height="`${height}px`" style="border: 1px solid transparent;" />
      <div v-show="show" class="download" @click="hanleDownload">
        下载二维码
      </div>
    </div>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import { getCode } from '@/api/params'
export default {
  name: 'Qrcode',
  data() {
    return {
      url: '',
      width: 300,
      height: 300,
      show: false,
      loading: true
    }
  },
  mounted() {
    this.initDownload()
  },
  methods: {
    hanleDownload() {
      const canvas = document.getElementById('canvas')
      canvas.toBlob((blob) => {
        saveAs(blob, 'Qr-code.jpg')
      })
    },
    async initDownload() {
      await this.initCode()
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      img.crossOrigin = 'Anonymous'
      img.src = this.url
      img.onload = () => {
        ctx.drawImage(img, 0, 0, this.width, this.height)
        this.loading = false
        this.show = true
      }
    },
    async initCode() {
      const res = await getCode()
      const { receipt_code } = res.data
      this.url = receipt_code
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  .gathering{
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 300px;
    .img-wrap{
      width: 100%;
      padding-bottom: 100%;
      position: relative;
      height: 0;
      overflow: hidden;
      background-color: #000;
      img {
        position: absolute;
        width: 100%;
        height: 100%;
      }
    }
    .download{
      width: 100%;
      display: block;
      text-align: center;
      line-height: 40px;
      cursor: pointer;
    }
  }
}
</style>
